
import { ref, reactive } from 'vue'
import { useRouter } from "vue-router"
import { useStore } from "vuex"

import {
    showModal,
    toast
} from "~/composables/util"

import {
    logout,
    updatepassword
} from "~/api/manager"

export function useRepassword() {
    const router = useRouter()
    const store = useStore()

    // 修改密码
    const formDrawerRef = ref(null)
    const form = reactive({
        oldpassword: '',
        password: '',
        repassword: ''
    })

    const rules = reactive({
        oldpassword: [
            {
                required: true,
                message: '旧密码不能为空',
                trigger: 'blur'
            },
        ],
        password: [
            {
                required: true,
                message: '新密码不能为空',
                trigger: 'blur'
            },
        ],
        repassword: [
            {
                required: true,
                message: '确认密码不能为空',
                trigger: 'blur'
            },
        ]
    })

    const formRef = ref(null)
    const onSubmit = () => {
        // 调用表单验证方法
        formRef.value.validate((valid) => {
            // 如果验证不通过
            if (!valid) {
                // 返回false，阻止后续代码执行
                return false
            }

            // 设置加载状态为true
            formDrawerRef.value.showLoading()

            // 调用更新密码的API
            updatepassword(form)
                .then(res => {
                    // 提示用户修改密码成功，并提示重新登陆
                    toast("修改密码成功,请重新登陆")

                    // 调用store的logout方法，进行登出操作
                    store.dispatch('logout')

                    // 跳转到登录页面
                    router.push("/login")
                })
                .finally(() => {
                    // 无论成功或失败，都设置加载状态为false
                    formDrawerRef.value.hideLoading()
                })
        })
    }

    const openRePasswordForm = () => formDrawerRef.value.open()

    return {
        formDrawerRef,
        form,
        rules,
        formRef,
        onSubmit,
        openRePasswordForm
    }
}

export function useLogout() {
    const router = useRouter()
    const store = useStore()

    // 退出登录
    function handleLogout() {
        showModal("是否要退出登录？").then(res => {
            logout().finally(() => {
                store.dispatch('logout')
                router.push("/login")   // 跳转回登录页面
                toast("退出登录成功")   // 提示退出登录成功
            })
        })
    }

    return {
        handleLogout
    }
}